import logging
from datetime import datetime

from formencode.validators import Int

from clutch.globals import C, G
from clutch.controllers import Controller
from clutch.decorators import expose, validate
from clutch.exceptions import ContinueTraversal
from clutch import api

from testapp.model import session, metadata
from testapp.controllers import tests
import testapp.model as m

log = logging.getLogger('testapp.controllers')

class Root(Controller):

    def __init__(self):
        self.tests = tests.TestController()

    @expose()
    def index(self):
        value = C.session.get('A', 0)
        C.session['A'] = value + 1
        return 'The value of A in the session is %s' % value

    @expose()
    def check_identity(self):
        log.info('testapp session  = %s', session)
        log.info('testapp metadata = %s', metadata)
        ep = api.call('id://')
        return ep

    @expose()
    def my_eh(self, a=None, _clutch_errors=None, **kw):
        return 'Validation Error Handler for index: a=%s, kw=%s' % (
            a, kw)

    @expose()
    @validate(a=Int(),
              error_handler=my_eh)
    def test1(self, a=None):
        return 'Hi test1! %s' % a

    @expose('test/index.html')
    def test(self):
        return dict(now=datetime.now())

    @expose()
    def foo(self, *l, **kw):
        return 'Foo, there! %s, %s' % (l, kw)

    def _on_404(self, *args, **kwargs):
        raise ContinueTraversal(SimpleDynamic(args[0]), args[1:])

class SimpleDynamic(Controller):

    def __init__(self, value):
        self.value = value

    @expose()
    def index(self, a=None):
        return 'Hello, %s (%s)' % (
            self.value, a)
